package com.mit.wx.controller;

import com.mit.wx.entity.Material;
import com.mit.wx.service.MaterialService;
import com.mit.wx.vo.BasicJsonResult;
import com.mit.wx.vo.EasyUIDataGrid;
import com.mit.wx.wx.dto.WxNewsItem;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

/**
 * 2018/10/12 Create by 郭文梁
 * MaterialController
 * 素材操作控制类
 *
 * @author 郭文梁
 * @date 2018/10/12
 */
@RestController
@RequestMapping("/material")
@Slf4j
public class MaterialController {
    private final MaterialService materialService;

    @Autowired
    public MaterialController(MaterialService materialService) {
        this.materialService = materialService;
    }

    /**
     * 创建素材
     *
     * @return BJR
     */
    @PostMapping("/create")
    public BasicJsonResult<Material> create(Material material, MultipartFile file) throws IOException {
        Material result = materialService.create(material, file);
        if (result == null) {
            return BasicJsonResult.error(1, "创建素材失败");
        } else {
            return BasicJsonResult.ok(result);
        }
    }

    /**
     * 分页查看素材
     *
     * @return EasyUI数据表格格式数据
     */
    @GetMapping("/page")
    public EasyUIDataGrid<Material> list(int page, int rows) {
        List<Material> materials = materialService.list(page, rows);
        long count = materialService.getCount();
        return EasyUIDataGrid.of(count, materials);
    }

    /**
     * 获取图文消息列表（远程微信端存储）
     *
     * @param page 页数
     * @param rows 煤业数量
     * @return EasyUI DataGrid分页格式数据
     */
    @GetMapping("/news")
    public EasyUIDataGrid<WxNewsItem> news(int page, int rows) throws IOException {
        return materialService.getNewsList((page - 1) * rows, rows);
    }

    /**
     * 删除素材
     *
     * @param id 素材Id
     * @return BJR
     */
    @PostMapping("/delete")
    public BasicJsonResult<Integer> delete(Integer id) {
        int delete = materialService.delete(id);
        return BasicJsonResult.ok("删除成功", delete);
    }
}


